package com.zxh.system.controller;

import com.zxh.system.domain.JsonResult;
import com.zxh.system.domain.ResultCode;
import com.zxh.system.entity.User;
import com.zxh.system.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.Optional;

@RestController
@RequestMapping("user")
public class UserController extends BaseController<User> {

    @Autowired
    private UserService userService;

    @PreAuthorize("hasAnyRole('ROLE_USER_SAVE','ROLE_ADMIN')")
    @PostMapping
    public JsonResult<User> save(@RequestBody User user) {
        userService.add(user);
        return JsonResult.EMPTY();
    }

    @PreAuthorize("hasAnyRole('ROLE_USER_ALL')")
    @GetMapping("{id}")
    public JsonResult<User> get(@PathVariable Long id){
        Optional<User> u = userService.get(id);
        if(u.isPresent())
            return new JsonResult<>(u.get());
        else
            return new JsonResult<>(ResultCode.NOT_DATA);
    }

    @PreAuthorize("permitAll()")
    @RequestMapping(value = "currentUserInfo",method = {RequestMethod.GET,RequestMethod.POST})
    public JsonResult<User> currentUserInfo(){
        User u = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        return new JsonResult<>(u);
    }
}
